package snowflake

import (
	"fmt"
	"github.com/sony/sonyflake" // 索尼公司的开源项目
	"github.com/spf13/viper"
	"time"
)

var (
	sonyFlake     *sonyflake.Sonyflake
	sonyMachineID uint16
)

func getMachineID() (uint16, error) {
	return sonyMachineID, nil
}

func Init() (err error) {
	// 从配置文件读取 起始时间和机器ID
	sonyMachineID = uint16(viper.GetInt("app.machine_id"))
	t, _ := time.Parse("2006-01-02", viper.GetString("app.start_time"))
	settings := sonyflake.Settings{
		StartTime: t,
		MachineID: getMachineID, // 返回一个机器ID
	}
	sonyFlake = sonyflake.NewSonyflake(settings)
	return
}

func GetID() (id uint64, err error) {
	if sonyFlake == nil {
		err = fmt.Errorf("snoy flake not inited")
		return
	}
	id, err = sonyFlake.NextID()
	return
}
